﻿using System;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;

namespace Core {
    /// <summary>
    /// 通过Addressables来加载资源
    /// </summary>
    public class AssetLoader {
        private AsyncOperationHandle<GameObject> mHandle;
        private static GameObject obj;
        public static GameObject LoadAsset(string name,Action onComplete = null) {
            var t = Addressables.InstantiateAsync(name);
            t.Completed += handle => {
                onComplete?.Invoke();
            };
            
            return t.WaitForCompletion();
        }


        /// <summary>
        /// 同步加载资源
        /// </summary>
        public static T LoadAsset<T>(string name) {
            var handle = Addressables.LoadAssetAsync<T>(name);
            return handle.WaitForCompletion();
        }

        /// <summary>
        /// 异步加载资源
        /// </summary>
        public static void LoadAssetAsync<T>(string name, Action<T> onComplete = null) where T : class {
            var handle = Addressables.InstantiateAsync(name);
            handle.Completed += operationHandle => {
                onComplete?.Invoke(operationHandle.Result as T);
            };
        }

        /// <summary>
        /// 同步实例化对象
        /// </summary>
        public static GameObject InstantiateGameObject(string name,Action<GameObject> onLoadedComplete = null,Transform parent = null) {
            var handle = Addressables.InstantiateAsync(name, parent);
            handle.Completed += operationHandle => {
                onLoadedComplete?.Invoke(operationHandle.Result as GameObject);
            };
            return handle.WaitForCompletion();
        }

        /// <summary>
        /// 异步实例化对象
        /// </summary>
        public static void InstantiateGameObjectAsync(string name, Action<GameObject> onComplete = null,Transform parent = null) {
            var handle = Addressables.InstantiateAsync(name, parent);
            handle.Completed += operationHandle => {
                onComplete?.Invoke(operationHandle.Result);
            };
        }
    }
}